package com.kaishengit.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.kaishengit.entity.Product;
import com.kaishengit.util.DBHelp;
import com.kaishengit.util.Page;
import com.kaishengit.util.RowMapper;

public class ProductDao {
	
	private DBHelp<Product> db = new DBHelp<Product>();
	
	public void save(Product pro){
		String sql = "insert into t_prod(prodname,price) values (?,?)";
		db.executeSQL(sql, pro.getProdName(),pro.getPrice());
	}
	
	public List<Product> findAll(){
		
		String sql = "select id,prodName,price from t_prod";
		return db.executeQueryForList(sql, new ProductRowMapper());
		
	}
	public List<Product> findByPage(Page page){
		String sql = "select id,prodName,price from t_prod limit ?,?";
		return db.executeQueryForList(sql, new ProductRowMapper(),page.getStartNum(),page.getPageSize());
		
	}
	public Product findById(int id){
		String sql = "select id,prodName,price from t_prod where id = ?";
		return db.executeQueryForObject(sql, new ProductRowMapper(), id);
		
	}
	private class ProductRowMapper implements RowMapper<Product>{

		public Product mapperRow(ResultSet rs) throws SQLException {
			Product prod = new Product();
			prod.setId(rs.getInt("id"));
			prod.setProdName(rs.getString("prodName"));
			prod.setPrice(rs.getFloat("price"));
			
			return prod;
		}
		
	}
	public void update(Product pro) {
		String sql = "update t_prod set prodName = ?,price = ? where id = ?";
		db.executeSQL(sql, pro.getProdName(),pro.getPrice(),pro.getId());
		
	}

	public void del(int id) {
		String sql = "delete from t_prod where id = ?";
		db.executeSQL(sql, id);
		
	}
	
	public int getTotalNums(){
		String sql = "select count(*) from t_prod";
		return db.executeQueryForCount(sql);
		
	}
	
}
